package m1_simple;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;

import java.io.IOException;
import java.util.Scanner;
import java.util.concurrent.TimeoutException;

public class Producer2 {
    public static void main(String[] args) throws IOException, TimeoutException {
        //连接rabbitmq服务器
        ConnectionFactory f = new ConnectionFactory();
        f.setHost("192.168.126.129");
        f.setPort(5672);    //5672是通信端
        f.setUsername("admin");
        f.setPassword("admin");

        Connection con = f.newConnection();
        Channel c = con.createChannel();
        //定义队列,或通知服务器想使用一个“helloworld”队列
        //服务器会找到这个队列，如果不存在，会服务器会新建队列
        c.queueDeclare("task_queue",true,false,false,null);
        while (true){
            //控制台输入的消息发送到rabbitmq
            System.out.println("输入消息:");
            String msg = new Scanner(System.in).nextLine();
            //如果输入的是"exit" 则结束生产者进程
            if("exit".equals(msg)){
                break;
            }
            //参数：exchange routingKey，props，body
            c.basicPublish("","task_queue", MessageProperties.PERSISTENT_TEXT_PLAIN,msg.getBytes());
            System.out.println("消息已发送:"+msg);
        }
        /**
        //发送消息
        //4个参数
        //  空串后面用到时在介绍，队列名，其他属性参数，消息数据
        c.basicPublish("","helloworld",null,"helloworld".getBytes());
        System.out.println("消息已经发送");
        */
        c.close();
        con.close();

   }
}
